from flask import Blueprint, render_template, request
from flask_login import login_required, current_user
from sqlalchemy import desc


from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Reagent
from datetime import datetime

bp = Blueprint('reagent', __name__, url_prefix='/reagent')


# 物资管理
@bp.get('/')
@authorize("system:reagent:main")
def main():
    return render_template('system/reagent/reagent.html')


# 信息分页查询
@bp.get('/data')
@authorize("system:reagent:main")
def data():
    # 获取请求参数
    reagentName = str_escape(request.args.get('reagentName', type=str))

    producer = str_escape(request.args.get('producer', type=str))

    filters = []
    if reagentName:
        filters.append(Reagent.reagentName.contains(reagentName))
    if producer:
        filters.append(Reagent.producer.contains(producer))

    query = db.session.query(
        Reagent
    ).filter(*filters).layui_paginate()

    return table_api(
        data=[{
            'id': reagent.id,
            'reagentName': reagent.reagentName,
            'thickness': reagent.thickness,
            'producer': reagent.producer,
            'volume': reagent.volume,
            'update_at': reagent.update_at,
            'description': reagent.description,
            'storage_condition': reagent.storage_condition
        } for reagent in query.items],
        count=query.total)


# 试剂增加
@bp.get('/add')
@authorize("system:reagent:add", log=True)
def add():
    reagent = Reagent.query.all()
    return render_template('system/reagent/add.html', reagent=reagent)


@bp.post('/save')
@authorize("system:reagent:add", log=True)
def save():
    req_json = request.get_json(force=True)
    reagentName = str_escape(req_json.get('reagentName'))
    thickness = str_escape(req_json.get('thickness'))
    volume = str_escape(req_json.get('volume'))
    producer = str_escape(req_json.get('producer'))
    storage_condition = str_escape(req_json.get('storage_condition'))
    description = str_escape(req_json.get('description'))

    description = '无' if not description else description

    if not reagentName or not thickness or not producer or not producer or not volume:
        return fail_api(msg="关键信息不得为空")

    reagent = Reagent(
        reagentName=reagentName,
        thickness=thickness,
        volume=volume,
        producer=producer,
        storage_condition=storage_condition,
        description=description
    )
    try:
        db.session.add(reagent)
        db.session.commit()
    except:
        db.session.rollback()
        return fail_api(msg="字段类型不匹配")
    return success_api(msg="增加成功")


# 删除试剂
@bp.delete('/remove/<int:id>')
@authorize("system:reagent:remove", log=True)
def delete(id):
    res = Reagent.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


#  编辑设备，这里主要是用来传递页面
@bp.get('/edit/<int:id>')
@authorize("system:reagent:edit", log=True)
def edit(id):
    reagent = curd.get_one_by_id(Reagent, id)
    return render_template('system/reagent/edit.html', reagent=reagent)


def get_current_time():
    create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return datetime.strptime(create_at, "%Y-%m-%d %H:%M:%S")


#  编辑设备信息
@bp.put('/update')
@authorize("system:reagent:edit", log=True)
def update():
    req_json = request.get_json(force=True)
    id = str_escape(req_json.get('id'))
    reagentName = str_escape(req_json.get('reagentName'))
    thickness = str_escape(req_json.get('thickness'))
    volume = str_escape(req_json.get('volume'))
    producer = str_escape(req_json.get('producer'))
    storage_condition = str_escape(req_json.get('storage_condition'))
    description = str_escape(req_json.get('description'))
    update_at = get_current_time()

    if not reagentName or not thickness or not producer or not storage_condition or not volume:
        return fail_api(msg="关键信息不得为空")

    try:
        Reagent.query.filter_by(id=id).update({
            'reagentName': reagentName,
            'thickness': thickness,
            'volume': volume,
            'producer': producer,
            'storage_condition': storage_condition,
            'description': description,
            'update_at': update_at
        })
        db.session.commit()
    except:
        return fail_api(msg="字段类型不匹配")
    return success_api(msg="更新成功")

